class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int size = intervals.size();
        sort(intervals.begin(), intervals.end(),
            [](const auto& v1, const auto& v2) {
                return v1[0] != v2[0] ? v1[0] < v2[0] : v1[1] < v2[1];
            });
        // for (auto r : intervals) {
        //     for (auto c : r)
        //         cout << c << ' ';
        //     cout << endl;
        // }

        vector<vector<int>> ret;
        for (int i = 0; i < size; i++)
        {
            while (i + 1 < size && intervals[i][0] == intervals[i + 1][0]) i++;
            int l = intervals[i][0];
            int r = intervals[i][1];
            while (i + 1 < size && r >= intervals[i + 1][0]) r = max(r, intervals[++i][1]);
            ret.push_back({ l, r });
        }
        return ret;
    }
};